import { showToast } from 'vant';
import i18n from '@/const/lang';

/**
 * 防抖
 * @param data Json格式数据
 * */
export const throttle = (callback: (v: any) => void, time: number) => {
    let timer: any = null;
    return function (v: any) {
        if (timer !== null) {
            clearTimeout(timer);
        }
        timer = setTimeout(() => {
            callback(v);
        }, time * 1000);
    };
};

/**
 * 复制
 * @param content 复制内容
 * */
export const copy = (text: any) => {
    if (navigator.clipboard) {
        // clipboard api 复制
        navigator.clipboard.writeText(text);
    } else {
        var textarea = document.createElement('textarea');
        document.body.appendChild(textarea);
        // 隐藏此输入框
        textarea.style.position = 'fixed';
        textarea.style.clip = 'rect(0 0 0 0)';
        textarea.style.top = '10px';
        // 赋值
        textarea.value = text;
        // 选中
        textarea.select();
        // 复制
        document.execCommand('copy', true);
        // 移除输入框
        document.body.removeChild(textarea);
    }
    showToast({
        message: (i18n.global as any).t('invite.test12'),
        position: 'top',
    });
};

export const toObject = (json: any) => {
    let result: any = {};
    for (const key in json) {
        if (Object.prototype.hasOwnProperty.call(json, key)) {
            const element = json[key];
            if (element.source) {
                result[key] = element.source;
                if (typeof element.source === 'string' && element.source.startsWith('(') && element.source.endsWith(') =>')) {
                    try {
                        result[key] = new Function(`return ${element.source}`)();
                    } catch (error) {
                        console.error(`${result[key]} is not a function`)
                    }
                }
            } else {
                if(Array.isArray(element.source)) {
                    result[key] = element;
                } else {
                    result[key] = toObject(element);
                }
            }
        }
    }
    return result;
};
